Understanding Activities and Their Responsibilities in Android
Course: Android App Development
Topic: Understanding Activities and Their Responsibilities
Course Link: Android App Development Course
Demo Link: Register for a Free Course Demo
Official Website: JustAcademy
1. Introduction to Android Activities
An Activity is one of the fundamental components of Android application development. It represents a screen with which users can interact to perform a particular task. For example, a login screen, registration screen, product details screen, or settings screen can each be implemented using an Activity.
Activities provide the entry point for user interaction with an application. They coordinate the user interface, respond to user actions, manage screen-related state, and interact with other Android components when necessary.
In modern Android applications, a single Activity can also host multiple screens implemented using Fragments or Jetpack Compose navigation. Therefore, an Activity does not necessarily represent every individual screen in an application.
Example of Activities in a Shopping Application
- LoginActivity: Allows users to sign in.
- HomeActivity: Displays products and categories.
- ProductDetailsActivity: Displays detailed information about a selected product.
- CheckoutActivity: Allows users to review their orders and proceed to payment.
- SettingsActivity: Provides application preferences and account settings.
2. What Is an Activity in Android?
An Activity is an Android application component that provides a window in which the application draws its user interface. The Android operating system manages the Activity lifecycle and determines when an Activity is created, resumed, paused, stopped, or destroyed.
Activities are generally implemented using Kotlin or Java. Their layouts can be created using XML layouts, Jetpack Compose, or other supported UI techniques.
Basic Kotlin Activity Example
package com.example.myapp
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val message = TextView(this)
message.text = "Welcome to Android Development"
message.textSize = 22f
setContentView(message)
}
}
Explanation:
AppCompatActivity provides an Activity implementation with AndroidX compatibility features.
onCreate() is called when the Activity instance is created.
Bundle? can contain previously saved instance state.
TextView displays text on the screen.
setContentView() sets the Activity's content view.
This example creates a simple Activity that displays a welcome message without requiring a separate XML layout.
3. Main Responsibilities of an Activity
An Activity has several responsibilities related to screen presentation, user interaction, lifecycle management, and coordination with other Android components.
3.1 Displaying the User Interface
An Activity provides a window for displaying the user interface. It can host buttons, text fields, images, lists, navigation elements, and other UI components.
For example, a login Activity may display an email field, password field, login button, and a link to the registration screen.
setContentView(R.layout.activity_main)
The statement above loads a layout resource named activity_main.xml as the Activity's content view.
3.2 Handling User Interactions
Activities coordinate user interactions by connecting UI elements to application logic. They may respond to button clicks, text input, menu selections, and other events.
val button = findViewById<Button>(R.id.btnSubmit)
button.setOnClickListener {
Toast.makeText(
this,
"Button clicked",
Toast.LENGTH_SHORT
).show()
}
This example displays a short message when the user clicks a button. In a real application, the click handler might validate input, request data, or navigate to another screen.
3.3 Managing the Activity Lifecycle
Android controls the lifecycle of an Activity. An Activity must respond appropriately when it becomes visible, receives user interaction, loses focus, moves into the background, or is recreated.
Lifecycle callbacks allow developers to perform suitable tasks at different stages, such as initializing UI components, registering listeners, pausing animations, and releasing resources.
3.4 Navigating Between Screens
Activities can initiate other Activities using Intents. This allows users to move between application features, such as navigating from a home screen to a profile screen.
val intent = Intent(this, ProfileActivity::class.java)
startActivity(intent)
Navigation can also be implemented using Fragments and Navigation Compose, depending on the application's architecture.
3.5 Managing Screen-Related State
Activities may need to preserve temporary interface information when the device rotates or the operating system recreates the Activity. Developers can use saved instance state, ViewModels, and persistent storage according to the type of data involved.
For example, a registration form should avoid losing entered information during a configuration change. A ViewModel can retain UI-related data across Activity recreation, while saved instance state can preserve small amounts of transient information.
3.6 Coordinating With Other Android Components
Activities can interact with services, content providers, broadcast receivers, repositories, and other application components. However, an Activity should not take responsibility for every business operation.
For example, an Activity can display weather information while a repository retrieves the data from an API. Long-running work should be delegated to suitable background-processing mechanisms instead of being performed directly on the main thread.
4. Understanding the Activity Lifecycle
The Activity lifecycle describes the different states an Activity passes through during its existence. Android invokes lifecycle callbacks to notify the Activity about important changes.
| Callback |
Purpose |
Typical Use |
onCreate() |
Initializes a newly created Activity. |
Set up the UI and initialize essential objects. |
onStart() |
Called when the Activity becomes visible. |
Prepare resources needed while visible. |
onResume() |
Called when the Activity enters the foreground and becomes interactive. |
Resume animations or interactive operations. |
onPause() |
Called when the Activity loses its resumed state. |
Pause work that should not continue while the Activity is not active. |
onStop() |
Called when the Activity is no longer visible. |
Stop visibility-dependent work and release unnecessary resources. |
onRestart() |
Called when a stopped Activity is about to start again. |
Prepare for the Activity to become visible again. |
onDestroy() |
Called when the Activity is being destroyed. |
Perform final cleanup when appropriate. |
Typical Lifecycle Flow
onCreate()
|
v
onStart()
|
v
onResume()
|
| Activity loses foreground interaction
v
onPause()
|
| Activity becomes completely invisible
v
onStop()
|
| Activity is reopened
v
onRestart()
|
v
onStart()
|
v
onResume()
This is a simplified lifecycle flow. The exact callbacks depend on the event that occurs. For example, an Activity may be paused and then resumed without entering the stopped state.
Lifecycle Implementation Example
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Log.d("ActivityLifecycle", "onCreate called")
}
override fun onStart() {
super.onStart()
Log.d("ActivityLifecycle", "onStart called")
}
override fun onResume() {
super.onResume()
Log.d("ActivityLifecycle", "onResume called")
}
override fun onPause() {
super.onPause()
Log.d("ActivityLifecycle", "onPause called")
}
override fun onStop() {
super.onStop()
Log.d("ActivityLifecycle", "onStop called")
}
override fun onDestroy() {
super.onDestroy()
Log.d("ActivityLifecycle", "onDestroy called")
}
}
Note: Add the appropriate android.util.Log import when needed. Lifecycle logging is useful for understanding callback order while testing an application.
5. Activity and User Interface Responsibilities
An Activity coordinates the UI, but good application design separates presentation from business logic and data management.
Recommended Responsibilities
- Initialize the screen and connect UI elements.
- Observe UI state supplied by a ViewModel.
- Forward user actions to suitable application logic.
- Respond to lifecycle events appropriately.
- Request navigation to other screens when necessary.
- Display loading indicators, error messages, and results.
Responsibilities That Should Usually Be Delegated
- Business rules: Place complex rules in suitable domain or business-logic classes.
- Data retrieval: Use repositories or data sources for database and network operations.
- Long-running tasks: Use appropriate asynchronous APIs and background-work mechanisms.
- Reusable UI: Use Fragments or Compose components when they improve modularity.
- Persistent data: Use suitable storage solutions rather than relying on Activity fields.
6. Creating an Activity in Android Studio
Android Studio provides tools for creating and configuring Activities. The exact menu names may vary by Android Studio version and project template.
Step 1: Create or Open a Project
Open Android Studio and create a new Android project or open an existing one. Choose Kotlin or Java according to the project requirements.
Step 2: Create an Activity Class
Create a Kotlin class that extends an appropriate Activity class, such as ComponentActivity or AppCompatActivity.
class ProfileActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profile)
}
}
Step 3: Create the Layout
Create the corresponding layout resource if you are using XML-based UI development. For example, activity_profile.xml can contain the profile screen's text, images, and buttons.
Step 4: Register the Activity
For Activities that are not automatically registered by the project configuration, declare the Activity inside the application's AndroidManifest.xml file.
<application
android:theme="@style/Theme.MyApp"
android:label="@string/app_name">
<activity
android:name=".ProfileActivity"
android:exported="false" />
</application>
Replace the theme and other project-specific values with the ones used by your application. An Activity that is launched only internally can commonly use android:exported="false". Components that must be launched by other applications need appropriate exported settings and security considerations.
Step 5: Launch the Activity
Launch the Activity from another Activity using an explicit Intent.
val intent = Intent(this, ProfileActivity::class.java)
startActivity(intent)
Ensure that the required imports are included and that the target Activity is registered when required.
7. Activity Responsibilities in a Real-World Example
Consider a simple login feature in an Android application. The Activity should primarily coordinate the user interface and user actions.
Example Login Activity
class LoginActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
val loginButton =
findViewById<Button>(R.id.loginButton)
loginButton.setOnClickListener {
Toast.makeText(
this,
"Login requested",
Toast.LENGTH_SHORT
).show()
}
}
}
This example demonstrates basic interaction only. It does not authenticate a user or securely validate credentials.
How Responsibilities Are Divided
| Component |
Responsibility |
| LoginActivity |
Displays the login UI and forwards the login action. |
| LoginViewModel |
Coordinates screen state and login-related UI logic. |
| AuthenticationRepository |
Coordinates communication with the authentication data source. |
| Authentication Service |
Validates credentials and manages authentication according to the backend's security design. |
This separation improves readability, testing, and maintainability. Actual authentication must be implemented securely using an appropriate backend or identity provider.
8. Activity vs. Fragment
Activities and Fragments are related Android components, but they serve different purposes.
| Feature |
Activity |
Fragment |
| Purpose |
Provides a window and an application interaction entry point. |
Provides a reusable portion of UI and its associated behavior. |
| Lifecycle |
Managed by the Android system. |
Managed in relation to its host and its own lifecycle. |
| Reuse |
Can be reused through navigation and explicit Intents. |
Can be reused in different Activity layouts or navigation flows. |
| Typical Use |
Top-level application container or entry point. |
Reusable UI section or independently managed screen area. |
| Communication |
Can communicate with other components through suitable mechanisms. |
Can communicate through shared ViewModels, callbacks, or navigation mechanisms. |
9. Common Mistakes When Working With Activities
9.1 Performing Long Operations on the Main Thread
Network requests, large database operations, and expensive computations on the main thread can make the application unresponsive. Use appropriate coroutine dispatchers, asynchronous APIs, and repositories.
9.2 Keeping Important Data Only in Activity Fields
Activity instances can be destroyed and recreated. Important data should be stored using ViewModels, saved instance state, or persistent storage according to its purpose and lifetime.
9.3 Ignoring Lifecycle Events
Failing to pause or clean up work at the appropriate lifecycle stage can cause unnecessary resource usage, duplicate listeners, or incorrect UI behavior.
9.4 Putting All Application Logic in One Activity
Large Activities that handle UI, networking, validation, database operations, and business rules become difficult to test and maintain. Divide responsibilities among suitable architecture components.
9.5 Incorrect Manifest Configuration
An Activity that is missing from the required manifest configuration may fail to launch. Incorrect exported settings can also create security risks or prevent intended external entry points from working.
9.6 Assuming onDestroy() Always Runs
The Android system can terminate an application's process without calling onDestroy() on every Activity. Save important data earlier and do not depend on this callback as the only way to preserve user information.
10. Best Practices for Managing Activities
- Keep Activity classes focused on UI coordination and navigation.
- Use ViewModels to manage UI-related state that must survive configuration changes.
- Use repositories to separate data access from the UI.
- Observe lifecycle-aware data and collect flows using lifecycle-aware APIs.
- Handle configuration changes and process recreation appropriately.
- Avoid storing Activity references in long-lived objects to prevent memory leaks.
- Use explicit Intents for internal Activity navigation where appropriate.
- Validate exported components and Intent filters carefully.
- Test lifecycle transitions, navigation, rotation, and background-to-foreground behavior.
- Follow current Android architecture and security recommendations.
11. Practical Exercise
Objective: Build a simple application containing a Home Activity and a Profile Activity.
Requirements
- Create a new Android project in Android Studio.
- Create a Home Activity with a welcome message and a Profile button.
- Create a Profile Activity with a heading and a Back button.
- Register the Profile Activity in the manifest if required by the project configuration.
- Use an explicit Intent to open the Profile Activity.
- Implement lifecycle logging in both Activities.
- Run the application and test navigation, rotation, and returning to the Home Activity.
Expected Outcome
The Home Activity should display the welcome message. Clicking the Profile button should open the Profile Activity. The Back button or device Back action should return the user to the previous screen, and lifecycle logs should help demonstrate Activity transitions.
12. Interview Questions and Answers
Q1. What is an Activity in Android?
Answer: An Activity is an Android application component that provides a window for displaying a user interface and coordinating user interaction.
Q2. What are the primary responsibilities of an Activity?
Answer: Its responsibilities include setting up the UI, handling user interactions, coordinating navigation, responding to lifecycle callbacks, and connecting the presentation layer with application logic.
Q3. What is the purpose of onCreate()?
Answer: The onCreate() callback initializes a newly created Activity. Developers commonly set up the UI and initialize essential screen-related objects in this method.
Q4. What is the difference between onStart() and onResume()?
Answer: onStart() indicates that the Activity is becoming visible. onResume() indicates that it has entered the resumed state and can interact with the user.
Q5. Can an application have multiple Activities?
Answer: Yes. An application can have multiple Activities, each serving a different purpose. Applications may also use a single Activity with Fragments or Compose navigation.
Q6. How can one Activity open another?
Answer: It can create an Intent targeting the destination Activity and call startActivity().
Q7. Why should business logic not be placed entirely inside an Activity?
Answer: Separating business logic improves maintainability, testability, code reuse, and lifecycle handling. ViewModels, repositories, and domain classes can take responsibility for appropriate parts of the application.
Q8. What happens when an Activity is recreated after device rotation?
Answer: Depending on the configuration and application setup, Android may destroy the old Activity instance and create a new one. ViewModels and saved instance state can help preserve the appropriate data.
Q9. What is the difference between an Activity and a Fragment?
Answer: An Activity provides an application window and entry point, while a Fragment represents a reusable UI section managed within a host Activity.
Q10. Why should developers avoid lengthy operations in lifecycle callbacks?
Answer: Expensive operations on the main thread can block rendering and user interaction. Appropriate background execution and asynchronous APIs help keep the application responsive.
13. Quick Revision Notes
- An Activity is a core Android component for user interaction.
- Activities provide a window for presenting the UI.
onCreate() initializes a new Activity instance.
onStart() indicates visibility, while onResume() indicates the resumed state.
onPause() and onStop() help manage transitions away from active or visible states.
- Intents can launch other Activities.
- ViewModels can preserve UI-related state across configuration changes.
- Repositories and other architecture components should handle appropriate data and business responsibilities.
- Activities must account for lifecycle changes and possible process termination.
- Good Activity design improves application reliability, readability, and maintainability.
14. Conclusion
Understanding Activities and their responsibilities is essential for building reliable Android applications. Activities coordinate user interfaces, user interactions, lifecycle events, and navigation between application components. Developers should keep Activity classes focused and delegate complex business logic and data operations to suitable architecture components.
By understanding lifecycle callbacks, managing state correctly, using Intents appropriately, and following Android development best practices, developers can create applications that are responsive, maintainable, and easier to test.
Learn Android App Development with JustAcademy
Explore the Android App Development course to strengthen your knowledge of Activities, lifecycle management, navigation, UI development, and other essential Android concepts.
Course Page: Explore the Android App Development Course
Book a Demo: Register for a Course Demo
Visit JustAcademy: https://www.justacademy.co/